package io.jsen.meta.diff.feature.annotation;

import io.jsen.meta.diff.exception.MetaAnnotationParserException;
import io.jsen.meta.diff.feature.parser.DefaultFieldControl;
import io.jsen.meta.diff.feature.FieldControl;
import io.jsen.meta.diff.feature.parser.ProxyDefaultFieldControl;
import io.jsen.meta.diff.field.MetaFieldDefine;
import io.jsen.meta.diff.obj.Convert;
import lombok.Data;

/**
 * MetaFieldFeature -> FeatureConfig
 *
 * @author jsen
 * @date 2021/09/18
 **/
@Data
public class FeatureConfig {
    private boolean ignore;
    private boolean uniqueKey;
    private String alias;
    private FieldControl fieldControl;


    @SuppressWarnings("rawtypes")
    public Convert getNativeConvert(MetaFieldDefine metaFieldDefine) {
        return fieldControl.nativeConvert(metaFieldDefine);
    }

    @SuppressWarnings("rawtypes")
    public Convert getMetaConvert(MetaFieldDefine metaFieldDefine) {
        return fieldControl.nativeConvert(metaFieldDefine);
    }


    public static FeatureConfig parse(MetaFieldFeature feature) {
        try {
            return build(feature.ignore(), feature.uniqueKey(), feature.alias(),
                    feature.fieldControl().newInstance());
        } catch (Exception e) {
            throw new MetaAnnotationParserException("注解解析异常" + feature, e);
        }
    }

    public static FeatureConfig build(boolean ignore, boolean uniqueKey, String alias, FieldControl control) {
        FeatureConfig config = new FeatureConfig();
        config.setIgnore(ignore);
        config.setUniqueKey(uniqueKey);
        config.setAlias(alias);
        if (control.getClass() != DefaultFieldControl.class) {
            control = new ProxyDefaultFieldControl(control);
        }
        config.setFieldControl(control);
        return config;
    }

    public static FeatureConfig empty() {
        return build(false, false, "", new DefaultFieldControl());
    }
}
